from typing import Dict, List, Optional
import pandas as pd
import numpy as np
from datetime import datetime
import requests
from textblob import TextBlob
import tweepy
from config.settings import AnalysisConfig

'''情绪分析器'''
class SentimentAnalyzer:
    """情绪分析器"""
    
    def __init__(self, config: AnalysisConfig):
        """
        初始化情绪分析器
        
        Args:
            config: 分析配置
        """
        self.config = config
        self.twitter_api = None
        self._init_twitter_api()
        
    def _init_twitter_api(self):
        """初始化Twitter API"""
        try:
            auth = tweepy.OAuthHandler(
                self.config.twitter_api_key,
                self.config.twitter_api_secret
            )
            auth.set_access_token(
                self.config.twitter_access_token,
                self.config.twitter_access_secret
            )
            self.twitter_api = tweepy.API(auth)
        except Exception as e:
            print(f"Twitter API initialization failed: {e}")
            
    def analyze_social_sentiment(self, symbol: str, lookback_hours: int = 24) -> Dict:
        """分析社交媒体情绪"""
        sentiment_scores = []
        
        try:
            # 获取Twitter数据
            if self.twitter_api:
                # 搜索相关推文
                query = f"#{symbol.replace('/', '')} OR #{symbol.split('/')[0]}"
                tweets = self.twitter_api.search_tweets(
                    q=query,
                    lang="en",
                    count=100,
                    tweet_mode="extended"
                )
                
                # 分析情绪
                for tweet in tweets:
                    blob = TextBlob(tweet.full_text)
                    sentiment_scores.append(blob.sentiment.polarity)
                    
            # 计算情绪指标
            if sentiment_scores:
                avg_sentiment = np.mean(sentiment_scores)
                sentiment_std = np.std(sentiment_scores)
                sentiment_count = len(sentiment_scores)
            else:
                avg_sentiment = 0
                sentiment_std = 0
                sentiment_count = 0
                
            return {
                'average_sentiment': avg_sentiment,
                'sentiment_std': sentiment_std,
                'sentiment_count': sentiment_count,
                'timestamp': datetime.now()
            }
            
        except Exception as e:
            print(f"Error analyzing social sentiment: {e}")
            return {
                'average_sentiment': 0,
                'sentiment_std': 0,
                'sentiment_count': 0,
                'timestamp': datetime.now()
            }
            
    def analyze_news_sentiment(self, symbol: str, lookback_hours: int = 24) -> Dict:
        """分析新闻情绪"""
        try:
            # 使用新闻API获取相关新闻
            # 这里需要实现具体的新闻API调用
            news_sentiment_scores = []
            
            # 示例：分析新闻标题情绪
            news_titles = []  # 从API获取的新闻标题列表
            for title in news_titles:
                blob = TextBlob(title)
                news_sentiment_scores.append(blob.sentiment.polarity)
                
            # 计算新闻情绪指标
            if news_sentiment_scores:
                avg_sentiment = np.mean(news_sentiment_scores)
                sentiment_std = np.std(news_sentiment_scores)
                sentiment_count = len(news_sentiment_scores)
            else:
                avg_sentiment = 0
                sentiment_std = 0
                sentiment_count = 0
                
            return {
                'average_sentiment': avg_sentiment,
                'sentiment_std': sentiment_std,
                'sentiment_count': sentiment_count,
                'timestamp': datetime.now()
            }
            
        except Exception as e:
            print(f"Error analyzing news sentiment: {e}")
            return {
                'average_sentiment': 0,
                'sentiment_std': 0,
                'sentiment_count': 0,
                'timestamp': datetime.now()
            }
            
    def analyze_market_fear_greed(self) -> Dict:
        """分析市场恐慌贪婪指数"""
        try:
            # 获取Fear & Greed指数
            # 这里需要实现具体的API调用
            
            return {
                'fear_greed_index': 50,  # 示例值
                'fear_greed_value': 'Neutral',
                'timestamp': datetime.now()
            }
            
        except Exception as e:
            print(f"Error analyzing fear and greed: {e}")
            return {
                'fear_greed_index': 50,
                'fear_greed_value': 'Neutral',
                'timestamp': datetime.now()
            }
            
    def get_overall_sentiment(self, symbol: str) -> Dict:
        """获取综合情绪分析结果"""
        # 获取各个维度的情绪数据
        social_sentiment = self.analyze_social_sentiment(symbol)
        news_sentiment = self.analyze_news_sentiment(symbol)
        market_sentiment = self.analyze_market_fear_greed()
        
        # 计算综合情绪分数
        sentiment_score = (
            social_sentiment['average_sentiment'] * 0.3 +  # 社交媒体权重
            news_sentiment['average_sentiment'] * 0.3 +    # 新闻权重
            (market_sentiment['fear_greed_index'] / 100) * 0.4  # 市场情绪权重
        )
        
        return {
            'overall_sentiment': sentiment_score,
            'social_sentiment': social_sentiment,
            'news_sentiment': news_sentiment,
            'market_sentiment': market_sentiment,
            'timestamp': datetime.now()
        }
